<?php

namespace App\Http\Controllers\Dashboard;

use App\Http\Controllers\Controller;
use App\Http\Requests\Dashboard\CourseIndexRequest;
use App\Http\Requests\Dashboard\CourseStoreRequest;
use App\Http\Requests\Dashboard\CourseUpdateRequest;

use App\Http\Resources\Dashboard\CourseAutoCompleteResource;

use App\Http\Resources\Dashboard\CourseResource;
use App\Models\Course;
use Illuminate\Http\Request;

class CourseController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @param CourseIndexRequest $request
     * @param Course $course
     * @return \Illuminate\Http\Resources\Json\AnonymousResourceCollection
     */
    public function index(CourseIndexRequest $request, Course $course)
    {
        $course = $course->withCount('skills');
        return CourseResource::collection($course->paginate($request->get('per_page', 15)));
    }

    public function autoComplete(Request $request, Course $course)
    {

        if ($request->filled('keyword')) {
            $course = $course->like('title', $request->keyword)->orLike('description', $request->keyword);
        }
        $course = $course->limit($request->get('limit', 5));
        return CourseAutoCompleteResource::collection($course->get());
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param CourseStoreRequest $request
     * @return CourseResource
     */
    public function store(CourseStoreRequest $request)
    {
        $course = new Course($request->only(['title', 'description', 'content', 'content_type', 'course_type', 'content_type', 'exp', 'depth']));
        $course->save();

        return new CourseResource($course);
    }

    public function show(Course $course)
    {
        return new CourseResource($course);
    }

    public function contentType()
    {
        return Course::CONTENT_TYPES;
    }

    public function courseTypes()
    {
        return Course::COURSE_TYPES;
    }

    /**
     * Update the specified resource in storage.
     *
     * @param CourseUpdateRequest $request
     * @param  \App\Models\Course $course
     * @return CourseResource
     */
    public function update(CourseUpdateRequest $request, Course $course)
    {
        $course->fill($request->only(['title', 'description', 'content', 'content_type', 'course_type', 'content_type', 'exp', 'depth']));
        $course->save();
        return new CourseResource($course);
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  \App\Models\Course $course
     * @return void
     * @throws \Exception
     */
    public function destroy(Course $course)
    {
        $course->delete();
    }
}
